//import {log} from "../finch-log";
const mime = require('./mime');
const fs = require('fs');
const path = require('path');
import {ServerResponse} from "http";



/**
 * response a download File;
 * @param res  response
 * @param downloadFilePath Download File Path
 * @param downloadFileName Download File Name
 */
function responseDownloadFile(res:ServerResponse, downloadFilePath:string, downloadFileName?:string)
{
    if(!fs.existsSync(downloadFilePath))
    {
        res.writeHead(404, {"Content-Type": "text/html"});
        res.write("404 :Can not found this Page !");
        res.end();
        return;
    }
    downloadFileName = downloadFileName ? downloadFileName:path.basename(downloadFilePath);
    let ext = path.extname(downloadFileName);
    ext = ext ? ext.slice(1) : 'unknown';
    let contentType = mime[ext] || 'text/plain';
    res.writeHead(200, {
        'Content-Type': contentType,
        'content-length': fs.statSync(downloadFilePath).size,
        'Content-Disposition': ('attachment;filename=' + encodeURI( downloadFileName))
    });
    let stream = fs.createReadStream(downloadFilePath);
    stream.pipe(res);
}
export {responseDownloadFile} ;